package com.xique.auth.service;

import com.xique.api.api.RemoteAccessTokenService;
import com.xique.api.api.domain.ApiThirdToken;
import com.xique.api.api.model.LoginApiThirdToken;
import com.xique.auth.bean.request.AccessTokenRequest;
import com.xique.common.core.constant.Constants;
import com.xique.common.core.constant.UserConstants;
import com.xique.common.core.domain.R;
import com.xique.common.core.enums.UserStatus;
import com.xique.common.core.exception.BaseException;
import com.xique.common.core.utils.SecurityUtils;
import com.xique.common.core.utils.StringUtils;
import com.xique.common.core.utils.sign.RsaUtils;
import com.xique.system.api.RemoteSystemLogService;
import com.xique.system.api.RemoteSystemUserService;
import com.xique.system.api.dto.SystemUserDTO;
import com.xique.system.api.model.LoginSystemUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * @author shd
 * @create 2021/11/11 16:46
 */
@Component
public class SystemLoginService {

    @Autowired
    private RemoteSystemLogService remoteSystemLogService;

    @Autowired
    private RemoteSystemUserService remoteSystemUserService;

    @Autowired
    private RemoteAccessTokenService remoteAccessTokenService;

    @Value("${xique.api.privateKey}")
    private String privateKey;

    /**
     * 登录
     */
    public LoginSystemUser login(String username, String password) {
        try {
            password = RsaUtils.decryptByPrivateKey(privateKey, password);
        } catch (Exception e) {
            throw new BaseException("密码解析错误");
        }
        // 用户名或密码为空 错误
        if (StringUtils.isAnyBlank(username, password)) {
            remoteSystemLogService.saveLoginInfo(username, Constants.LOGIN_FAIL, "用户/密码必须填写", UserConstants.Platform.API);
            throw new BaseException("用户/密码必须填写");
        }
        // 密码如果不在指定范围内 错误
        if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                || password.length() > UserConstants.PASSWORD_MAX_LENGTH) {
            remoteSystemLogService.saveLoginInfo(username, Constants.LOGIN_FAIL, "用户密码不在指定范围", UserConstants.Platform.API);
            throw new BaseException("用户密码不在指定范围");
        }
        // 用户名不在指定范围内 错误
        if (username.length() < UserConstants.USERNAME_MIN_LENGTH
                || username.length() > UserConstants.USERNAME_MAX_LENGTH) {
            remoteSystemLogService.saveLoginInfo(username, Constants.LOGIN_FAIL, "用户名不在指定范围", UserConstants.Platform.API);
            throw new BaseException("用户名不在指定范围");
        }
        // 查询用户信息
        R<LoginSystemUser> userResult = remoteSystemUserService.getUserInfo(username);
        if (R.FAIL == userResult.getCode()) {
            throw new BaseException(userResult.getMsg());
        }

        if (StringUtils.isNull(userResult) || StringUtils.isNull(userResult.getData())) {
            remoteSystemLogService.saveLoginInfo(username, Constants.LOGIN_FAIL, "登录用户不存在", UserConstants.Platform.API);
            throw new BaseException("登录用户：" + username + " 不存在");
        }
        LoginSystemUser userInfo = userResult.getData();
        SystemUserDTO user = userResult.getData().getSystemUser();
        if (UserStatus.DELETED.getCode().equals(user.getDelFlag())) {
            remoteSystemLogService.saveLoginInfo(username, Constants.LOGIN_FAIL, "对不起，您的账号已被删除", UserConstants.Platform.API);

            throw new BaseException("对不起，您的账号：" + username + " 已被删除");
        }
        if (UserStatus.DISABLE.getCode().equals(user.getStatus())) {
            remoteSystemLogService.saveLoginInfo(username, Constants.LOGIN_FAIL, "用户已停用，请联系管理员", UserConstants.Platform.API);
            throw new BaseException("对不起，您的账号：" + username + " 已停用");
        }
        if (!SecurityUtils.matchesPasswordWithOldVersion(password, user.getLoginName(), user.getSalt(), user.getPassword())) {
            remoteSystemLogService.saveLoginInfo(username, Constants.LOGIN_FAIL, "用户密码错误", UserConstants.Platform.API);
            throw new BaseException("用户不存在/密码错误");
        }
        if (!UserStatus.SUPPORT_API.getCode().equals(user.getSupportApi())) {
            remoteSystemLogService.saveLoginInfo(username, Constants.LOGIN_FAIL, "不支持三方获取接口信息", UserConstants.Platform.API);
            throw new BaseException("不支持三方获取接口信息");
        }
        remoteSystemLogService.saveLoginInfo(username, Constants.LOGIN_SUCCESS, "登录成功", UserConstants.Platform.API);
        return userInfo;
    }

    public void logout(String loginName) {
        remoteSystemLogService.saveLoginInfo(loginName, Constants.LOGOUT, "退出成功", UserConstants.Platform.API);
    }

    public LoginApiThirdToken getAccessToken(AccessTokenRequest request) {
        if (StringUtils.isAnyBlank(request.getAppId(), request.getAppSecret())) {
            throw new BaseException("appId/appSecret必须填写");
        }
        R<LoginApiThirdToken> result = remoteAccessTokenService.getThirdAccount(request.getAppId(), request.getAppSecret());
        if (R.FAIL == result.getCode()) {
            throw new BaseException(result.getMsg());
        }
        if (StringUtils.isNull(result) || StringUtils.isNull(result.getData())) {
            throw new BaseException("账号：" + request.getAppId() + " 不存在");
        }
        LoginApiThirdToken loginApiThirdToken = result.getData();
        ApiThirdToken token = loginApiThirdToken.getToken();
        if (UserStatus.DELETED.getCode().equals(token.getDelFlag())) {
            throw new BaseException("对不起，您的账号：" + token.getAppId() + " 已被删除");
        }
        if (UserStatus.USER_DISABLE.getCode().equals(token.getStatus())) {
            throw new BaseException("对不起，您的账号：" + token.getAppId() + " 已停用");
        }
        return loginApiThirdToken;
    }

}
